<template>
  <a-row class="card-nopd-out-container department-container">
    <a-col :span="openSide ? 3 : 0" class="tree-box pt-20">
      <a-button type="primary" @click="handleDeptAdd('sysSupDepartment')" v-if="!treeData.length && hasOptBtn('system:dept:add')">{{$t('sysManage.newDepart')}}</a-button>
      <side-tree v-if="openSide && treeData.length" :defaultSelect="selectedKeys" :openSide="openSide" @onSelect="onTreeSelect" @onEdit="onTreeEdit" @onDelete="onTreeDelete" :treeData="treeData" />
      <div v-if="isEnvLocal" class="mt-20">
        <a-button block type="primary" @click="syncData(syncDataAry)"> {{$t('common.sync')}}</a-button>
      </div>
    </a-col>
    <a-col :span="openSide ? 21: 24" :class="['table-box', 'pt-20', 'pr-20',{'pl-20': !openSide}]" v-if="selectedKeys.length">
      <div :class="['icon-out', {'close': !openSide}]" @click="()=> {openSide= !openSide}">
        <double-left-outlined v-if="openSide" />
        <double-right-outlined v-else />
      </div>
      <div class='blue-line'>{{selectedDpdName}}</div>
      <div class="list-operate2" v-if="hasOptBtn('system:dept:add')">
        <a-button type="primary" @click="handleDeptAdd('sysDepartment')">{{ $t('sysManage.newSubDepart') }}</a-button>
      </div>
      <a-table rowKey="id" class="mt-15" :loading="loading" bordered size="small" :dataSource="dataSource" :columns="columns" @change="handleTableChange" :pagination="ipagination" :scroll="{x: 800, y: hasOptBtn('system:dept:add') ? 'calc(100vh - 390px)' : 'calc(100vh - 338px)'}">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'operate'">
            <span class="table-operate-container">
              <a-button v-if="hasPermission('system:dept:edit')" type="link" class="primary-link" @click="onTreeEdit(record, true)">{{$t('common.editor')}}</a-button>
              <a-divider type="vertical" />
              <a-button v-if="hasPermission('system:dept:delete')" type="link" class="warning-link" @click="handleDelete(record.id, true)">{{$t('common.del')}}</a-button>
            </span>
          </template>
        </template>
      </a-table>
    </a-col>
    <commone-modal v-if="modalName=='sysDepartment'" ref="modalForm" layout="vertical" tableName="sysDepartment" :cloSapn="24" :modalTitle="$t('sysManage.subDepart')" @ok="otherOperate">
    </commone-modal>
    <commone-modal v-else ref="modalForm" tableName="sysSupDepartment" :cloSapn="24" :modalTitle="$t('sysManage.depart')" @ok="otherOperate">
    </commone-modal>
    <SyncDataModal ref="syncDataModalRef" />
  </a-row>
</template>

<script>
import { filterObj, hasPermission } from '@/utils'
import { cloneDeep } from 'lodash'
import axios from '@/utils/request'
import SideTree from './modules/sideTree.vue'
import { ListMixinPm } from '@/mixin/listMixinPm.js'
import CommoneModal from '@/components/commonModal/normalModal.vue'
import { DoubleLeftOutlined, DoubleRightOutlined } from '@ant-design/icons-vue'
import { store } from '@/store'
import { normalColumns, localColumns } from './modules/config'
import SyncDataModal from '@/components/syncModal/syncDataModal.vue'
import { message } from 'ant-design-vue'
export default {
  name: 'sysDepartment',
  components: {
    SideTree,
    DoubleLeftOutlined,
    DoubleRightOutlined,
    CommoneModal,
    SyncDataModal
  },
  mixins: [ListMixinPm],
  data () {
    return {
      openSide: true,
      selectedKeys: [],
      columns: [],
      url: {
        list: '/api/system/dept/list',
        treeList: '/api/system/dept/treeselect',
        delete: '/api/system/dept/delete',
        sync: '/api/system/iot/sync-cloud-data'
      },
      modalName: 'sysDepartment',
      treeData: [],
      selectedDpdName: '',
      operateType: 'add',
      syncDataAry: [
        { syncIotCloudDataType: 'ihs:system:dept' }
      ]
    }
  },
  methods: {
    hasPermission,
    hasOptBtn (permission) {
      return !this.isEnvLocal && this.hasPermission(permission)
    },
    getQueryParams () {
      if (!this.selectedKeys.length) {
        return false
      } else {
        let param = cloneDeep(this.queryParam)
        return filterObj(param)
      }
    },
    handleDeptAdd (tableName) {
      this.operateType = 'add'
      this.modalName = tableName
      this.$nextTick(() => {
        if (tableName === 'sysDepartment') {
          this.handleEdit({ parentId: this.selectedKeys[0] }, false)
        } else {
          this.handleAdd()
        }
      })
    },
    onTreeSelect (selectedKeys, selectedNodes) {
      if (selectedKeys.length) {
        this.selectedDpdName = selectedNodes[0].label
        this.selectedKeys = selectedKeys
        this.queryParam.parentId = selectedKeys[0]
        this.loadData(1)
      } else {
        this.initPage()
      }
    },
    initPage () {
      this.selectedDpdName = ''
      this.selectedKeys = []
      this.queryParam.parentId = null
      this.ipagination.current = 1
      this.ipagination.pageSize = 10
    },
    onTreeEdit (info, isInner) {
      this.operateType = isInner ? null : 'edit'
      this.modalName = info.parentId ? 'sysDepartment' : 'sysSupDepartment'
      this.$nextTick(() => {
        this.handleEdit(info)
      })
    },
    onTreeDelete (id) {
      this.operateType = 'delete'
      this.handleDelete(id, true)
    },
    async otherOperate (params) {
      if (this.operateType == 'delete') {
        this.initPage()
      } else if (this.operateType == 'edit') {
        if (params.id == this.selectedKeys[0]) this.selectedDpdName = params.name
      }
      await this.getTreeData()
      this.loadData()
    },
    async getTreeData () {
      const res = await axios.postAction(this.url.treeList, {})
      if (res.success) this.treeData = res.data
      store.dispatch('getDepart')
    },
    initModalSelectOptions () {
      return {
        parentId: this.treeData
      }
    },
    async syncData (params) {
      this.$refs.syncDataModalRef.visible = true
      try {
        let res = await axios.postAction(this.url.sync, params)
        if (res.success) {
          message.success(res.msg || '数据同步成功')
          this.getTreeData()
        } else {
          message.error(res.msg || '同步失败请稍后重试')
        }
        this.$refs.syncDataModalRef.visible = false
      } catch {
        message.error('同步失败请稍后重试')
        this.$refs.syncDataModalRef.visible = false
      }
    },
  },
  created () {
    this.columns = this.isEnvLocal ? localColumns : normalColumns
    this.getTreeData()
  }
}
</script>